package com.yunform.framework.hibernate;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class SQLDao extends HibernateDaoSupport{
	
	public List<Object> select(final String sql){
		return this.select(sql, null);
	}
	
	public List<Object> select(final String sql, final Map<String,Object> parameters){
		return super.getHibernateTemplate().executeWithNativeSession(new HibernateCallback<List<Object>>() {
			@SuppressWarnings("unchecked")
			public List<Object> doInHibernate(Session session) throws HibernateException {
				Query query = session.createSQLQuery(sql);
				if(parameters!=null){
					for(Map.Entry<String,Object> ele : parameters.entrySet() ){
						query.setParameter(ele.getKey(), ele.getValue());
					}
				}
				return (List<Object>)query.list();
			}
		});
		
	}
	
	/**
	 * 执行DDL语句用
	 * @param sql
	 * @return
	 */
	public int update(final String sql){
		return super.getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session) throws HibernateException {
				Query query = session.createSQLQuery(sql);
				return query.executeUpdate();
			}
		});
	}
	
	public int update(final String sql, final Map<String,Object> parameters){
		return super.getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session) throws HibernateException {
				Query query = session.createSQLQuery(sql);
				String[] ps =query.getNamedParameters();
				if(parameters!=null){
					for(Map.Entry<String,Object> ele : parameters.entrySet() ){
						query.setParameter(ele.getKey(), ele.getValue());
					}
				}
				return query.executeUpdate();
			}
		});
	}
	
	
}
